package org.csc.chaincode.sample;

import org.apache.commons.lang3.StringUtils;
import org.csc.chaincode.AbstractChainCode;
import org.csc.chaincode.ChainCodeLog;
import org.hyperledger.fabric.shim.ChaincodeStub;

import java.util.List;

public class SampleChainCode extends AbstractChainCode {

    /**
     * 初始化一些配置文件
     * @param args 可以修改一些配置
     */
    public static void main(String[] args) {
        new SampleChainCode().start(args);
    }

    /**
     * 实例化链码的时候调用
     * @param stub 参数实体
     * @return
     */
    @Override
    public Response init(ChaincodeStub stub) {

        ChainCodeLog.log(stub);

        if (StringUtils.isBlank(stub.getFunction())) {
            return super.newErrorResponse(String.format("函数名称 =》%s 不存在", stub.getFunction()));
        }

        switch (stub.getFunction()) {
            case AbstractChainCode.INIT:
                this.init(stub, stub.getParameters());
                break;
            default:
                return super.newErrorResponse(String.format("函数名称 =》%s 不存在", stub.getFunction()));
        }

        return super.newErrorResponse();
    }

    /**
     * 对链码执行一些操作的时候调用
     * @param stub 参数实体
     * @return
     */
    @Override
    public Response invoke(ChaincodeStub stub) {

        ChainCodeLog.log(stub);

        if (StringUtils.isBlank(stub.getFunction())) {
            return super.newErrorResponse(String.format("函数名称 =》%s 不存在", stub.getFunction()));
        }

        switch (stub.getFunction()) {
            case AbstractChainCode.QUERY:
                this.query(stub, stub.getParameters());
                break;
            case AbstractChainCode.PUT:
                this.put(stub, stub.getParameters());
                break;
            case AbstractChainCode.DEL:
                this.del(stub, stub.getParameters());
                break;
            case AbstractChainCode.INVOKE_CHAIN_CODE:
                this.invokeChainCode(stub.getFunction(), stub.getParameters(), null);
                break;
            default:
                return super.newErrorResponse(String.format("函数名称 =》%s 不存在", stub.getFunction()));
        }

        return super.newErrorResponse();
    }

    @Override
    public Response init(ChaincodeStub stub, List<String> args) {
        return super.newSuccessResponse();
    }

    @Override
    public Response query(ChaincodeStub stub, List<String> args) {
        return super.newSuccessResponse();
    }

    @Override
    public Response del(ChaincodeStub stub, List<String> args) {
        return super.newSuccessResponse();
    }

    @Override
    public Response put(ChaincodeStub stub, List<String> args) {
        return super.newSuccessResponse();
    }

    @Override
    public Response up(ChaincodeStub stub, List<String> args) {
        return super.newSuccessResponse();
    }

    @Override
    public Response invokeChainCode(String chainCodeName, List<String> args, String channel) {
        return super.newSuccessResponse();
    }

}
